package com.lizonghui.googleplay.protocol;

import com.lizonghui.googleplay.base.BaseProtocol;
import com.lizonghui.googleplay.bean.CategoryInfoBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/23.
 * 这里的协议解析使用结点解析，加title对象和内容数组对象都作为bean存到一个集合中返回
 */
public class CategoryProtocol extends BaseProtocol<List<CategoryInfoBean>> {
    @Override
    public List<CategoryInfoBean> parseJsonString(String resultJsonString) {
        //由于这里的协议返回的结构和我们定义的不一样，所以不能用Gson解析
        //现在是展示listView-->dataSet.size == item条目总数
        /**
         * 1bean解析
         * 2泛型解析
         * 3结点解析-->android sdk自带解析方式
         */
        try {
            List<CategoryInfoBean> categoryInfoBeans = new ArrayList<>();

            JSONArray rootJsonArray = new JSONArray(resultJsonString);
            //遍历集合
            for (int i = 0; i < rootJsonArray.length(); i++) {
                JSONObject itemJsonObject = rootJsonArray.getJSONObject(i);
                String title = itemJsonObject.getString("title");//title结点
                CategoryInfoBean titleBean = new CategoryInfoBean();
                titleBean.title = title;
                titleBean.isTitle = true;

                //加入集合中
                categoryInfoBeans.add(titleBean);

                JSONArray infoJsonArray = itemJsonObject.getJSONArray("infos");//infos结点
                for (int j = 0; j < infoJsonArray.length(); j++) {
                    JSONObject infoJsonObject = infoJsonArray.getJSONObject(j);
                    String name1 = infoJsonObject.getString("name1");
                    String name2 = infoJsonObject.getString("name2");
                    String name3 = infoJsonObject.getString("name3");
                    String url1 = infoJsonObject.getString("url1");
                    String url2 = infoJsonObject.getString("url2");
                    String url3 = infoJsonObject.getString("url3");

                    CategoryInfoBean infoBean = new CategoryInfoBean();
                    infoBean.name1 = name1;
                    infoBean.name2 = name2;
                    infoBean.name3 = name3;
                    infoBean.url1 = url1;
                    infoBean.url2 = url2;
                    infoBean.url3 = url3;

                    categoryInfoBeans.add(infoBean);

                }
            }
            return categoryInfoBeans;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getInterfaceKey() {
        return "category";
    }
}
